﻿using System.Linq.Extensions;
using System.Linq.PageList;
using Dyao.Book.Contract;
using Dyao.Book.Entity;
using Dyao.Repository.Abstractions;

namespace Dyao.Book.Repository
{
    using Foundation.Replacement;

    /// <summary>
    /// 任务中心配置
    /// </summary>
    public class TaskCenterSettingsRepository : DataRepository<TaskCenterSettingsEntity, string>, ITaskCenterSettingsRepository
    {
        /// <summary>
        /// 分页获取任务中心配置信息
        /// </summary>
        /// <param name="pageFilter">分页筛选器</param>
        /// <param name="cancellationToken">取消操作的通知</param>
        /// <returns>返回任务中心配置</returns>
        public async Task<IPageList<TaskCenterSettingsEntity>> GetPageListAsync(IPageFilter<TaskCenterSettingFilterDto> pageFilter, CancellationToken cancellationToken = default)
        {
            var query = GetQueryable()
                //模糊查询
                .WhereIf(s => s.DisplayName.Contains(pageFilter.Filter.SearchText), !string.IsNullOrEmpty(pageFilter.Filter.SearchText))
                .WhereIf(s => s.Category == pageFilter.Filter.TaskCenterCategory, pageFilter.Filter.TaskCenterCategory.HasValue)
                .OrderOrThenBy(x => x.CreateDateTime, false)
                //返回不追踪的集合
                .AsNoTracking();
            return await query.ToPageListAsync(pageFilter, cancellationToken);
        }

        #region  // override methods

        public override async Task<TaskCenterSettingsEntity> InsertAsync(TaskCenterSettingsEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            CompletedAppKey(entity);

            return await base.InsertAsync(entity, autoSave, cancellationToken);
        }

        public override async Task InsertRangeAsync(IEnumerable<TaskCenterSettingsEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            foreach (var entity in entities)
            {
                CompletedAppKey(entity);
            }

            await base.InsertRangeAsync(entities, autoSave, cancellationToken);
        }

        protected void CompletedAppKey(TaskCenterSettingsEntity entity)
        {
            if (string.IsNullOrWhiteSpace(entity.AppKey))
            {
                entity.AppKey = "DyaoBook";
            }
        }

        #endregion //end override methods
    }
}
